import matplotlib.pyplot as plt
import imageio


x = [1, 2, 3, 4, 4, 4, 4, 3, 2, 1, 1, 1, 1]
y = [1, 1, 1, 1, 2, 3, 4, 4, 4, 4, 3, 2, 1]
time = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]


def create_frame(t):
    fig = plt.figure(figsize=(6, 6))
    plt.plot(x[:(t+1)], y[:(t+1)], color = 'grey' )
    plt.plot(x[t], y[t], color = 'black', marker = 'o' )
    plt.xlim([0,5])
    plt.xlabel('x', fontsize = 14)
    plt.ylim([0,5])
    plt.ylabel('y', fontsize = 14)
    plt.title(f'Relationship between x and y at step {t}',
              fontsize=14)
    plt.savefig(f'./my_images/img_{t}.png', 
                transparent = False,  
                facecolor = 'white'
               )
    plt.close()


for t in time:
    create_frame(t)


import os
files = os.listdir('my_images')
 
# assume that your images that you 
# want to make the GIF are under the my_images folder
images_path = [os.path.join('my_images',file) for file in files]
 
# fps are the frames per second
frames = []
for img in images_path:
    frames.append(imageio.imread(img))

imageio.mimsave('./example.gif', # output gif
                frames,          # array of input frames
                fps = 5)         # optional: frames per second


# Если вы хотите, чтобы GIF останавливался после последнего кадра,
# добавьте параметр loop=1 в метод mimsave.
# imageio.mimsave('./example.gif', 
#                 frames, 
#                 fps = 5, 
#                 loop = 1)